// import Log from 'electron-log';

import { ipcMain, app, session, clipboard, shell, dialog} from 'electron';
import * as nodeStorage from 'node-localstorage';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import https from 'https'
import Utils from '../utils/utils';
import Log from 'electron-log';
import {machineIdSync} from 'node-machine-id'

// 接收标识为synchronous-message的消息，然后返回'pong'
ipcMain.on('synchronous-message', (event: any, arg: any) => {
    event.returnValue = 'pong'
})

ipcMain.on('net-config', (event: any, arg: any) => {
    const IS_DEV = process.env.NODE_ENV === 'development';
    const netUrl = IS_DEV ? path.join(app.getAppPath(), './public/netConfig.json') : path.join(app.getAppPath(), './build/netConfig.json');
    event.returnValue = fs.readFileSync(netUrl);
})

ipcMain.on('set-logout-time', (event: any, arg: any) => {
    let Days = 30;
    let exp = new Date();
    let date = exp.getTime() + Days * 24 * 60 * 60 * 1000;
    arg.expirationDate = date;

    (session.defaultSession as any).cookies.set(arg, (error: any) => {
        if (error) {
            return Promise.reject(false)
        } else {

            return Promise.resolve(true);
        }
    })
})


ipcMain.on('report-os', (event: any, arg: any) => {

    let osc = {
        '获取计算机名称： ': os.hostname(),
        '获取操作系统类型：': os.type(),
        '获取操作系统平台： ': os.platform(),
        '获取CPU架构： ': os.arch(),
        '获取操作系统版本号： ': os.release(),
        '获取系统当前运行的时间： ': os.uptime(),
        '系统总内存量： ': (os.totalmem() / 1024 / 1024 / 1024).toFixed(1) + 'G'
    }
    
    event.returnValue = osc;
})


ipcMain.on('get-logout-time', async (event: any, arg: any) => {
    let ret = await getLogoutTime(arg);

    // Log.error('取出来的时间',ret)

    event.returnValue = ret;
})

var getLogoutTime = (args: any) => {
    return new Promise(function (resolve, reject) {
        (session.defaultSession as any).cookies.get(args, (error: any, cookies: any) => {
            // Log.error(JSON.stringify(cookies),'---取得值')
            if (cookies.length > 0) {
                resolve(cookies[0]['value']);
            } else {
                resolve(cookies);
            }
        })
    })
}


var storages = {};
var globalStorage:any = {}

ipcMain.on('init-storage', (event: any, arg: any) => {
    const userPath = app.getPath('userData');
    const localStoragePath = path.join(userPath, path.sep, 'sd/') + arg.userId;
    // Log.error(localStoragePath, '----localstorage-------path', arg);
    fs.existsSync(localStoragePath) === false && mkdirs(localStoragePath);
    storages[arg.userId] = new nodeStorage.LocalStorage(localStoragePath);
});
ipcMain.on('init-global-storage', (event: any, arg: any) => {
    const userPath = app.getPath('userData');
    const localStoragePath = path.join(userPath, path.sep, 'sd/') + 'global';
    // Log.error(localStoragePath, '----localstorage-------path', arg);
    fs.existsSync(localStoragePath) === false && mkdirs(localStoragePath);
    globalStorage= new nodeStorage.LocalStorage(localStoragePath);
});

//获取缓存数据大小
ipcMain.on('cache-size', (event: any, arg: any) => {
    const userPath = app.getPath('userData');
    const localStoragePath = path.join(userPath, path.sep, 'sd/') + arg.userId;

    // Log.error(Utils.getPathSize(localStoragePath),'-----文件大小----')
    event.returnValue = Utils.getPathSize(localStoragePath);
})

ipcMain.on('error-encrypted', (event: any, arg: any) => {
    Log.error('error-encrypted', JSON.stringify(arg));
})

ipcMain.on('message-log', (event: any, arg: any) => {
    Log.info('message-log-->', JSON.stringify(arg));
})

// arg:{userId,type}
ipcMain.on('set-localstorage', (event: any, arg: any) => {
    if (arg.userId && storages[arg.userId]) {
        storages[arg.userId].setItem(arg.userId + '_' + arg.type, JSON.stringify(arg.value));

        // console.log('set-localstorage----hahahahhahahahahah', arg, 33333333333333333333333333333)
    }
    event.returnValue = true;
})

ipcMain.on('get-localstorage', (event: any, arg: any) => {

    if (storages[arg.userId]) {
        event.returnValue = storages[arg.userId].getItem(arg.userId + '_' + arg.type);
    }
});

ipcMain.on('clear-localstorage', (event: any, arg: any) => {
    if (storages[arg.userId]) {
        event.returnValue = storages[arg.userId].removeItem(arg.userId + '_' + arg.type);
    }else{
        event.returnValue = storages[arg.userId].clear();
    }
});


ipcMain.on('set-globalstorage', (event: any, arg: any) => {
    const {name,value } = arg || {}
    if( name ){
        console.log('set storage',name, value)
        globalStorage.setItem(name, value )
    }
    event.returnValue = true;
})

ipcMain.on('get-globalstorage', (event: any, arg: any) => {
    const {name,value } = arg || {}
    if (name) {
        event.returnValue = globalStorage.getItem(name);
    }
    event.returnValue = null;
});

ipcMain.on('clear-globalstorage', (event: any, arg: any) => {
    const {name,value } = arg || {}
    if (name) {
        event.returnValue = globalStorage.removeItem(name);
    }else{
        event.returnValue = globalStorage.clear();
    }
});



ipcMain.on('get-os', (event: any, arg: any) => {
    let osStr: string = os.platform();
    if (osStr == 'darwin') {
        osStr = 'Mac';
    } else if (osStr == 'win32') {
        osStr = 'Windows';
    } else {
        osStr = "Web";
    }
    event.returnValue = osStr;
})

ipcMain.on('get-device-id', (event: any, arg: any) => {
    event.returnValue = machineIdSync().substring(0, 16);
})

ipcMain.on('copy-text', (event, text) => {
    clipboard.writeText(text); // 将文本复制到剪贴板
    console.log(`Text copied to clipboard: ${text}`);
});
ipcMain.on('open-url',(event, url:string)=>{
    shell.openExternal(url); // 替换为你需要打开的网址
})

// 监听渲染进程发送的“另存为”请求
ipcMain.handle("save-file", async (event, { url, name }):Promise<{success:boolean,message?:string, file?:string}> => {
    const { filePath } = await dialog.showSaveDialog({
        title: "另存为",
        defaultPath: name,
        filters: [{ name: "All Files", extensions: ["*"] }]
    });
    if (!filePath) return { success: false, message: "用户取消保存" };

    return new Promise((resolve, reject) => {
        const file = fs.createWriteStream(filePath);
        https.get(url, (response) => {
            if (response.statusCode !== 200) {
                return reject({ success: false, message: `请求失败，状态码：${response.statusCode}` });
            }
            response.pipe(file);
            file.on("finish", () => {
                file.close();
                resolve({ success: true, file:filePath });
            });
        }).on("error", (err) => {
            fs.unlink(filePath, () => {}); // 删除未完整下载的文件
            reject({ success: false, message: err.message });
        });
    });
});
ipcMain.handle('abc', async (event, arg) => {
    return 'abc'
})
ipcMain.handle('set-cookie', (event, arg) =>{
    let cookies = session.defaultSession.cookies
    if( cookies ){
        return cookies.set(arg)
    }
    return Promise.resolve(null)
});

ipcMain.handle('get-cookie',  (event, arg) =>{
    let cookies = session.defaultSession.cookies;
    if( cookies ){
        return cookies.get(arg)
    }
    return Promise.resolve(null)
})
ipcMain.handle('get-locale',  (event, arg) =>{
    return app.getLocale()
})
ipcMain.handle('get-app-path',  (event, arg) =>{
    return app.getAppPath()
})
ipcMain.handle('get-version',  (event, arg) =>{
    return app.getVersion()
})

/**循环创建文件夹 */
var mkdirs = (dirpath: string) => {
    if (!fs.existsSync(path.dirname(dirpath))) {
        mkdirs(path.dirname(dirpath));
    }
    fs.mkdirSync(dirpath);
}

// var child_process = require('child_process');
// var child = child_process.fork(path.join(app.getAppPath(), './public/dataProcess.js'));
// child.on('message', (m:any)=>{
// console.log('message from child: ' + JSON.stringify(m));
// });
// child.send({from: 'parent'});
